#include "../header.h"

//1.双进程
//2.共享内存段

int main(int argc, char const *argv[])
{
     //1.创建一块共享内存 - 大小 + 权限
    int shmid = shmget(IPC_PRIVATE,1024,0600);
    printf("shmid = %d\n",shmid);

    //2.映射-内核自动分配,可用地址。flg = 0  标志位0。
    char * shaddr = shmat(shmid,0,0);
    if(shaddr == NULL)
    {
        perror("映射失败!\n");
    }

    //双任务
    pid_t pid = fork();
    if(pid < 0)
        exit(-1);
    //父进程空间
    if(pid > 0)
    {
        //3 写数据 - 字符串函数
        char * str = "this is msg test???";
        strncpy(shaddr,str,strlen(str));
        //防止孤儿进程。
        wait(NULL);
        //5.解除映射
        shmdt(shaddr);
        //6.销毁共享内存段。
        shmctl(shmid,IPC_RMID,NULL);
        system("ipcs -m");
    }
    if (pid == 0)
    {
        //4.读数据
        char buf[128] = "";
        strncpy(buf,shaddr,sizeof(buf));
        printf("this is child process: buf:%s\n",buf);
        printf("this is child process:%d\n",getpid());
    }
  

    return 0;
}
